// HTMX 配置和自定义功能
document.addEventListener('DOMContentLoaded', function() {
    // 设置 HTMX 默认请求头
    document.body.addEventListener('htmx:configRequest', function(event) {
        const token = localStorage.getItem('token');
        if (token && !isAuthRequest(event.detail.path)) {
            event.detail.headers['token'] = token;
        }
    });

    // 处理认证失败
    document.body.addEventListener('htmx:responseError', function(event) {
        if (event.detail.xhr.status === 401) {
            localStorage.removeItem('token');
            window.location.href = '/login';
        }
    });

    // 登录成功后保存token
    document.body.addEventListener('htmx:afterRequest', function(event) {
        if (event.detail.successful && event.detail.elt.id === 'login-form') {
            const response = JSON.parse(event.detail.xhr.responseText);
            if (response.token) {
                localStorage.setItem('token', response.token);
                window.location.href = '/dashboard';
            }
        }
    });
});

// 检查是否是认证相关请求
function isAuthRequest(path) {
    return path.includes('/login') || path.includes('/register');
}

// 复制功能
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        showToast('复制成功！');
    }).catch(function(err) {
        console.error('复制失败:', err);
        showToast('复制失败，请手动复制');
    });
}

// 显示提示消息
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type}`;
    toast.textContent = message;
    toast.style.position = 'fixed';
    toast.style.top = '20px';
    toast.style.right = '20px';
    toast.style.zIndex = '9999';
    toast.style.minWidth = '200px';
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// 切换开关功能
function toggleSwitch(element) {
    element.classList.toggle('active');
    const isActive = element.classList.contains('active');
    const settingName = element.getAttribute('data-setting');
    
    // 这里可以发送HTMX请求保存设置
    htmx.ajax('POST', '/settings/update', {
        values: { [settingName]: isActive },
        headers: { 'token': localStorage.getItem('token') }
    });
}

// 导航切换
function switchTab(tabName) {
    // 更新导航状态
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
    
    // 加载对应内容
    htmx.ajax('GET', `/${tabName}`, {
        target: '#main-content',
        headers: { 'token': localStorage.getItem('token') }
    });
}

// 常用词分类切换
function switchCategory(category, element) {
    // 更新分类按钮状态
    document.querySelectorAll('.category-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    element.classList.add('active');
    
    // 加载对应分类的词汇
    htmx.ajax('GET', `/common-words/category/${category}`, {
        target: '#words-container',
        headers: { 'token': localStorage.getItem('token') }
    });
}

// 插入常用词到输入框
function insertWord(word) {
    const textarea = document.querySelector('#conversation-input');
    if (textarea) {
        const cursorPos = textarea.selectionStart;
        const textBefore = textarea.value.substring(0, cursorPos);
        const textAfter = textarea.value.substring(cursorPos);
        textarea.value = textBefore + word + textAfter;
        textarea.selectionStart = textarea.selectionEnd = cursorPos + word.length;
        textarea.focus();
    }
}

// 生成对话
function generateConversation() {
    const input = document.querySelector('#conversation-input').value;
    const selectedWords = Array.from(document.querySelectorAll('.word-tag.selected')).map(el => el.textContent);
    
    if (!input.trim()) {
        showToast('请输入对话内容', 'error');
        return;
    }
    
    htmx.ajax('POST', '/conversation/generate', {
        values: { 
            input: input,
            selectedWords: selectedWords.join(',')
        },
        target: '#conversation-output',
        headers: { 'token': localStorage.getItem('token') }
    });
}

// 选择词汇标签
function toggleWordSelection(element) {
    element.classList.toggle('selected');
}

// 检查登录状态
function checkAuth() {
    const token = localStorage.getItem('token');
    const currentPath = window.location.pathname;
    
    if (!token && currentPath !== '/login' && currentPath !== '/register' && currentPath !== '/') {
        window.location.href = '/login';
        return false;
    }
    
    if (token && (currentPath === '/login' || currentPath === '/register')) {
        window.location.href = '/dashboard';
        return false;
    }
    
    return true;
}

// 退出登录
function logout() {
    localStorage.removeItem('token');
    window.location.href = '/login';
}

// 初始化检查
document.addEventListener('DOMContentLoaded', function() {
    checkAuth();
});